//
//  YoucApiError.m
//  YoucApi
//
//  Created by Liam on 12-10-3.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "YoucApiError.h"
#import "CmnMacro.h"

@implementation YoucApiError

static NSDictionary * codeDict = nil;
static NSDictionary * stringCodeDict = nil;
static NSDictionary * descDict = nil;

+ (void)initDescription
{
	if (codeDict == nil)
	{
		codeDict = [[NSDictionary dictionaryWithObjectsAndKeys:
					 @"Success",				[NSNumber numberWithInt:YoucApiErrorSuccess],
					 @"Unknown",				[NSNumber numberWithInt:YoucApiErrorUnkown],
					 nil] retain];
	}
	
	if (stringCodeDict == nil)
	{
		stringCodeDict = [[NSMutableDictionary dictionary] retain];
		
		for (NSNumber * key in [codeDict allKeys])
		{
			[(NSMutableDictionary*)stringCodeDict setObject:key forKey:[codeDict objectForKey:key]];
		}
	}
	
	if (descDict == nil)
	{
		descDict = [[NSDictionary dictionaryWithObjectsAndKeys:
					 @"操作成功",					[NSNumber numberWithInt:YoucApiErrorSuccess],
					 @"请求超时",					[NSNumber numberWithInt:YoucApiErrorRequestTimeOut],
					 @"用户取消",					[NSNumber numberWithInt:YoucApiErrorUserCancelled],
					 @"请求连接失败",				[NSNumber numberWithInt:YoucApiErrorRequestConnect],
					 @"尚未登录",					[NSNumber numberWithInt:YoucApiErrorUserNotLogin],
					 @"错误的数据返回",			[NSNumber numberWithInt:YoucApiErrorInvalidResponse],
					 //@"邮箱已被注册",				[NSNumber numberWithInt:YoucApiErrorUserEmailExists],
					 //@"昵称已被注册",				[NSNumber numberWithInt:YoucApiErrorNicknameExists],
					 //@"用户名或密码错误",			[NSNumber numberWithInt:YoucApiErrorInvalidUserNameOrPassword],
					 @"未知错误",					[NSNumber numberWithInt:YoucApiErrorUnkown],
					 nil] retain];
	}
}

- (void)dealloc
{
	[super dealloc];
}

+ (id)errorWithStringCode:(NSString*)stringCode userInfo:(NSDictionary *)dict
{
	[YoucApiError initDescription];
	
	NSNumber * numCode = [stringCodeDict objectForKey:stringCode];
	if (!numCode)
		numCode = [NSNumber numberWithInt:YoucApiErrorUnkown];
	
	return [[[YoucApiError alloc] initWithDomain:YoucApiErrorDomain code:[numCode intValue] userInfo:dict] autorelease];
}

+ (id)errorWithCode:(NSInteger)code userInfo:(NSDictionary *)dict
{
	[YoucApiError initDescription];
	
	return [[[YoucApiError alloc] initWithDomain:YoucApiErrorDomain code:code userInfo:dict] autorelease];
}

- (NSString *)localizedDescription
{
	NSString * desc = nil;
	
	desc = [descDict objectForKey:[NSNumber numberWithInt:[self code]]];

	if (desc == nil)
		desc = [super localizedDescription];
	
	return desc;
}

@end